import os
import sqlite3
import threading
from contextlib import contextmanager

class DatabaseManager:
    _instance = None
    _lock = threading.Lock()
    _local = threading.local()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(DatabaseManager, cls).__new__(cls)
                    cls._instance._db_path = None
        return cls._instance

    def init_app(self, db_path):
        """初始化数据库路径"""
        self._db_path = db_path
        self.init_db()

    def get_db_path(self):
        """获取数据库路径"""
        return self._db_path

    @contextmanager
    def get_connection(self):
        """获取数据库连接（线程安全）"""
        if not hasattr(self._local, 'db'):
            self._local.db = sqlite3.connect(
                self._db_path,
                detect_types=sqlite3.PARSE_DECLTYPES
            )
            self._local.db.row_factory = sqlite3.Row

        try:
            yield self._local.db
        except Exception:
            self._local.db.rollback()
            raise
        else:
            self._local.db.commit()

    def init_db(self):
        """初始化数据库表"""
        with self.get_connection() as db:
            db.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    username TEXT UNIQUE NOT NULL,
                    password TEXT NOT NULL
                )
            ''')

            db.execute('''
                CREATE TABLE IF NOT EXISTS sync_dirs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER NOT NULL,
                    local_path TEXT NOT NULL,
                    ftp_host TEXT NOT NULL,
                    ftp_user TEXT NOT NULL,
                    ftp_pass TEXT NOT NULL,
                    ftp_path TEXT NOT NULL,
                    sync_strategy TEXT DEFAULT 'local_priority',
                    sync_status TEXT DEFAULT 'pending',
                    last_sync TIMESTAMP,
                    FOREIGN KEY (user_id) REFERENCES users (id)
                )
            ''')

            db.execute('''
                CREATE TABLE IF NOT EXISTS sync_history (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    sync_dir_id INTEGER NOT NULL,
                    filename TEXT NOT NULL,
                    path TEXT NOT NULL,
                    direction TEXT NOT NULL,
                    operation TEXT NOT NULL,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (sync_dir_id) REFERENCES sync_dirs (id)
                )
            ''')

            db.commit()

# 创建全局实例
db_manager = DatabaseManager() 